# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : running_info_schema.py
# Time       ：2023/11/3 14:05
# Author     ：YangYong
# version    ：python 3.10
# Description：运行日志序列化类
"""
import json

from marshmallow import fields
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema


def get_process(process_instance_id):
    """计算任务进度"""
    from apis.orderlines.models import TaskInstance
    from sqlalchemy import desc
    from public.logger import logger
    from apis.orderlines.schema.task_schema import TaskInstanceSchema
    from public.base_model import session_scope

    try:
        with session_scope() as session:
            objs = session.query(TaskInstance).filter(
                TaskInstance.process_instance_id == process_instance_id,
                TaskInstance.active == 1).all()

            obj = session.query(TaskInstance).filter(
                TaskInstance.process_instance_id == process_instance_id
            ).order_by(desc(TaskInstance.task_index_id)).first()
        task_instance_info = TaskInstanceSchema().dump(obj)
        task_index_id = task_instance_info.get('task_index_id')
        process = round(task_index_id / len(objs) * 100)
        return 100 if process > 100 else process
    except Exception as e:
        logger.error(f'获取任务进度失败::{e}')
        return 100


class ProcessInfoSchema(SQLAlchemyAutoSchema):
    name = fields.String()
    status = fields.String()
    progress = fields.Function(lambda obj: get_process(obj.process_instance_id))
    process_instance_id = fields.String()


def get_color(task_status):
    status_color = {
        "SUCCESS": "#2bae85",
        "FAILURE": "#de3f7c",
        "SKIP": "#ec7696",
        "STOP": "#d2d97a",
        "RETRY": "#fba414",
        "PENDING": "#fbf2e3",
        "RUNNING": "#29b7cb"
    }
    return status_color.get(task_status) or "#ffffff"


def get_icon(task_status):
    icons = {
        "SUCCESS": "Select",
        "FAILURE": "CloseBold",
        "SKIP": "SemiSelect",
        "STOP": "SwitchButton",
        "RETRY": "Warning",
        "PENDING": "#fbf2e3",
        "RUNNING": "Loading"
    }
    return icons.get(task_status) or "CloseBold"


def get_task_status(task_status):
    task_status_dict = {
        "SUCCESS": "运行成功",
        "FAILURE": "运行失败",
        "SKIP": "运行跳过",
        "STOP": "运行停止",
        "RETRY": "运行重试",
        "PENDING": "运行排队",
        "RUNNING": "运行中"
    }
    return task_status_dict.get(task_status) or '运行失败'


class TaskNodeInfoSchema(SQLAlchemyAutoSchema):
    task_name = fields.String()
    start_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")
    color = fields.Function(lambda obj: get_color(obj.task_status))
    icon = fields.Function(lambda obj: get_icon(obj.task_status))


class RunningTaskSchema(SQLAlchemyAutoSchema):
    task_name = fields.String()
    task_status = fields.Function(lambda obj: get_task_status(obj.task_status))
    task_result = fields.Function(lambda obj: json.loads(obj.task_result) if obj.task_result else {})
    task_error = fields.Function(lambda obj: json.loads(obj.task_error) if obj.task_error else {})
    start_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")
    end_time = fields.DateTime(format="%Y-%m-%d %H:%M:%S")
